package org.ns.socket.client;

import org.ns.socket.client.codec.SocketDecodeHandler;
import org.ns.socket.client.codec.SocketEncodeHandler;
import org.ns.socket.client.handler.BioSocketHandler;
import org.ns.socket.client.handler.NioSocketHandler;
import org.ns.socket.client.handler.SocketReaderHandler;

import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo {

    public static void main(String[] args) throws Exception{
        ExecutorService worker = Executors.newFixedThreadPool(10);
        // 客户端的使用可以是NIO 也可以 BIO，这里看最终的使用方式

        // Client client = new Client(worker, NioSocketHandler.class);
        Client client = new Client(worker, BioSocketHandler.class);


        client.setSocketDecodeHandler(new SocketDecodeHandler() {
            @Override
            public void decode(ByteBuffer in, List<Object> out) {
                if (in.readable() == 0) {
                    return;
                }
                byte[] data = new byte[in.readable()];
                in.read(data);
                out.add(new String(data, Charset.forName("UTF-8")));
            }
        });

        client.setSocketEncodeHandler(new SocketEncodeHandler<String>() {
            @Override
            public void encode(String msg, ByteBuffer out) {
                out.write(msg.getBytes(Charset.forName("UTF-8")));
            }
        });

        client.setSocketReaderHandler(new SocketReaderHandler<String>() {
            @Override
            public void handler(SocketContext socketContext, String msg) {
                System.out.println(msg);
            }
        });


        client.connect("www.qxiu.com", 80);

        client.write("GET / HTTP/1.1\r\n\r\n");

        Thread.sleep(1000);
        client.close();
        worker.shutdown();
    }
}
